﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Web;
using System.IO;
using System.Xml;
using System.Xml.Schema;

namespace MPMusicVids.Importer
{
    public static class CleanXML
    {       
        //Download the file, save it as text
        public static XmlDocument Get(string url)
        {

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(@url);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            using (StreamReader sr = new StreamReader(res.GetResponseStream()))
            {
                string xmlData = sr.ReadToEnd();
                xmlData = xmlData.Replace("\n", Environment.NewLine);
                if (File.Exists(@"C:\tmp.xml"))
                    File.Delete(@"C:\tmp.xml");
                File.WriteAllText(@"C:\tmp.xml", xmlData);
            }
            return clean();
        }

        //scrub and read it
        private static XmlDocument clean()
        {
            List<char> charsToSubstitute = new List<char>();
            charsToSubstitute.Add((char)0x19);
            charsToSubstitute.Add((char)0x1C);
            charsToSubstitute.Add((char)0x1D);

            string fileText = File.ReadAllText(@"C:\tmp.xml");
            foreach (char c in charsToSubstitute)
                fileText = fileText.Replace(Convert.ToString(c), string.Empty);

            XmlDocument doc = new XmlDocument();
            MemoryStream ms = new MemoryStream(System.Text.ASCIIEncoding.UTF8.GetBytes(fileText));
            XmlTextReader reader = new XmlTextReader(ms);
            doc.Load(reader);
            if (File.Exists(@"C:\tmp.xml"))
                File.Delete(@"C:\tmp.xml");
            return doc;      
        }
    }
}